﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace IsAvailBr
{
    public class IsAvailQuery
    {

        #region Propriedades
        public string Ip { get; set; }
        public IsAvailVersao Versao { get; set; }
        public IsAvailCookie Cookie { get; set; }
        public Idioma Idioma { get; set; }
        public ulong Id { get; set; }
        public string Dominio { get; set; }
        public bool EnviarSugestoes { get; set; } 
        #endregion

        #region Factories
        public IsAvailQuery(string dominio, IsAvailVersao versao = 0, Idioma idioma = Idioma.Portugues, bool enviarSugestoes = false)
        {
            this.Dominio = dominio;
            this.Versao = versao;
            this.Idioma = idioma;
            this.EnviarSugestoes = enviarSugestoes;
        } 
        #endregion

        #region Métodos
        public string TraduzirQuery(IsAvailServico servico)
        {
            string queryFormat = "{0} {1} {2} {3} {4} {5} {6}";
            string ipFormat = "[{0}]";

            if (this.Id == 0 && this.Cookie != null)
            {
                this.Id = this.Cookie.QueryId;
            }
            else if (this.Id > 0 && this.Cookie == null)
            {
                this.Cookie = servico.ObterCookie(this.Id);
            }
            else
            {
                this.Id = IsAvailQuery.GerarNovoId();
                this.Cookie = servico.ObterCookie(this.Id);
            }

            string ip = string.IsNullOrEmpty(this.Ip) ? string.Empty : string.Format(ipFormat, this.Ip);
            string sugestao = this.Versao == IsAvailVersao.V1 ? Convert.ToByte(this.EnviarSugestoes).ToString() : string.Empty;
            return string.Format(queryFormat,
                ip, // [ip]
                ((int)this.Versao).ToString(), // <version>
                BitConverter.ToString(this.Cookie.CookieId).Replace("-", "").ToLower(), // <cookie>
                ((int)this.Idioma).ToString(), // <lang>
                this.Id.ToString(), // <qid>
                this.Dominio, // <fqdn>
                sugestao) // [<sugggest>]
                .Trim();
        } 
        #endregion

        public static ulong GerarNovoId()
        {
            string retorno = string.Empty;
            byte[] buffer = Guid.NewGuid().ToByteArray();
            for (int i = 0; i < buffer.Length; i++)
            {
                if (retorno.Length >= 10)
                    break;
                retorno += buffer[i].ToString();
            }
            return ulong.Parse(retorno.Substring(0, 10));
        }
    }
}
